package com.hx.er.common.logic;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.hx.er.common.util.StringUtil;

public class UserLoginInfoUtil {
	private static Map<String, Integer> userLoginMap = new HashMap<String, Integer>();
	private static Date originalDate;

	/**
	 * @param key
	 * @return
	 */
	public synchronized static int userLoginCount(String key) {
		if (originalDate == null) {
			originalDate = new Date();
		} else {
			// 获取原日期和当前日期的年、月、日
			Calendar cal = Calendar.getInstance();
			cal.setTime(originalDate);
			int originalYear = cal.get(Calendar.YEAR);
			int originalMonth = cal.get(Calendar.MONTH);
			int originalDateOfMonth = cal.get(Calendar.DAY_OF_MONTH);

			cal = Calendar.getInstance();
			int newYear = cal.get(Calendar.YEAR);
			int newMonth = cal.get(Calendar.MONTH);
			int newDateOfMonth = cal.get(Calendar.DAY_OF_MONTH);

			// 如果日期已经变化，原来保存的全部信息全部刷新
			if (originalYear != newYear || originalMonth != newMonth || originalDateOfMonth != newDateOfMonth) {
				userLoginMap.clear();
				originalDate = cal.getTime();
			}
		}

		// 判断是否已经存在该用户记录
		if (!userLoginMap.containsKey(key)) {
			userLoginMap.put(key, 1);
			return 1;
		} else {
			int newCount = userLoginMap.get(key) + 1;
			userLoginMap.put(key, newCount);
			return newCount;
		}
	}

	public static int getUserLoginCount(String key) {
		if (!userLoginMap.containsKey(key)) {
			return 0;
		} else {
			return userLoginMap.get(key);
		}
	}

	public static String getClientIP(HttpServletRequest request) {
		String ip = request.getHeader("X-Real-IP");

		if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}

		if (StringUtil.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}

		return ip;
	}

	public static long convertIpToLong(String ipStr) {
		long[] ip = new long[4];
		int position1 = ipStr.indexOf(".");
		int position2 = ipStr.indexOf(".", position1 + 1);
		int position3 = ipStr.indexOf(".", position2 + 1);
		ip[0] = Long.parseLong(ipStr.substring(0, position1));
		ip[1] = Long.parseLong(ipStr.substring(position1 + 1, position2));
		ip[2] = Long.parseLong(ipStr.substring(position2 + 1, position3));
		ip[3] = Long.parseLong(ipStr.substring(position3 + 1));
		// ip1*256*256*256+ip2*256*256+ip3*256+ip4
		return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3];
	}

	/**
	 * 是否是本地IP
	 * 
	 * @param strIp
	 * @return
	 */
	public static boolean isLocal(String strIp) {
		if ("127.0.0.1".equals(strIp))
			return true;
		long l = convertIpToLong(strIp);
		if (l >= 3232235520L)
			return l <= 3232301055L;
		return (l >= 167772160L) && (l <= 184549375L);
	}
}
